<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="商品名称" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="价格" prop="productPrice">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入价格"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品详情" prop="productDetail">
        <el-input
          v-model="queryParams.productDetail"
          placeholder="请输入商品详情"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品描述" prop="productDesc">
        <el-input
          v-model="queryParams.productDesc"
          placeholder="请输入商品描述"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery" >搜索</el-button>
        <el-button icon="el-icon-refresh-right" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPerm="['menu_add']"
        >新增</el-button>
      </el-col>

      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="handleQuery" />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" :content="showSearch ? '隐藏搜索' : '显示搜索'" placement="top">
          <el-button size="mini" circle icon="el-icon-search" @click="showSearch=!showSearch" />
        </el-tooltip>
      </div>
    </el-row>

    <el-table v-loading="loading" :data="productList" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="商品编号" align="center" prop="productId" />
      <el-table-column label="商品名称" align="center" prop="productName" :show-overflow-tooltip="true" />
      <el-table-column label="商品价格" align="center" prop="productPrice" :show-overflow-tooltip="true" />
      <el-table-column label="拥有者ID" align="center" prop="ownerId" :show-overflow-tooltip="true" />
      <el-table-column label="拥有者姓名" align="center" prop="ownerName" width="120" />
      <el-table-column label="卖家姓名" align="center" prop="salerMobile" width="120" />
      <el-table-column
        label="操作"
        align="center"
        width="180"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleEdit(scope.row)"
            v-hasPerm="['user_edit']"
          >修改</el-button>
          <el-button
            v-if="scope.row.id !== 1"
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDel(scope.row)"
            v-hasPerm="['user_del']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-key"
            @click="handleResetPwd(scope.row)"
            v-hasPerm="['user_reset']"
          >重置</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改菜单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="720px">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="商品名称" prop="productName">
              <el-input v-model="form.productName" placeholder="请输入商品名称" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品价格" prop="productPrice">
              <el-input v-model="form.productPrice" placeholder="请输入商品价格" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="商品介绍" prop="productDesc">
              <el-input v-model="form.productDesc" placeholder="请输入商品介绍" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="卖家手机" prop="salerMobile">
              <el-input v-model="form.salerMobile" placeholder="请输入卖家手机号" />
            </el-form-item>
          </el-col>
          <el-row>
            <el-col :xs="24" :md="12" :style="{height: '350px'}">
              <vue-cropper
                ref="cropper"
                :img="options.img"
                :info="true"
                :autoCrop="options.autoCrop"
                :autoCropWidth="options.autoCropWidth"
                :autoCropHeight="options.autoCropHeight"
                :fixedBox="options.fixedBox"
                @realTime="realTime"
              />
            </el-col>
            <el-col :xs="24" :md="12" :style="{height: '350px'}">
              <div class="avatar-upload-preview">
                <img :src="previews.url" :style="previews.img" />
              </div>
            </el-col>
          </el-row>
          <br />
          <el-row>
            <el-col :lg="2" :md="2">
              <el-upload action="#" :http-request="requestUpload" :show-file-list="false" :before-upload="beforeUpload">
                <el-button size="small">
                  上传
                  <i class="el-icon-upload el-icon--right"></i>
                </el-button>
              </el-upload>
            </el-col>
            <el-col :lg="{span: 1, offset: 2}" :md="2">
              <el-button icon="el-icon-plus" size="small" @click="changeScale(1)"></el-button>
            </el-col>
            <el-col :lg="{span: 1, offset: 1}" :md="2">
              <el-button icon="el-icon-minus" size="small" @click="changeScale(-1)"></el-button>
            </el-col>
            <el-col :lg="{span: 1, offset: 1}" :md="2">
              <el-button icon="el-icon-refresh-left" size="small" @click="rotateLeft()"></el-button>
            </el-col>
            <el-col :lg="{span: 1, offset: 1}" :md="2">
              <el-button icon="el-icon-refresh-right" size="small" @click="rotateRight()"></el-button>
            </el-col>
            <el-col :lg="{span: 2, offset: 6}" :md="2">
              <el-button type="primary" size="small" @click="uploadImg()">提 交</el-button>
            </el-col>
          </el-row>
<!--          <el-col :span="12">-->
<!--            <el-form-item label="菜单名称" prop="name">-->
<!--              <el-input v-model="form.name" placeholder="请输入菜单名称" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item v-if="form.type != 'F'" label="路由地址" prop="path">-->
<!--              <el-input v-model="form.path" placeholder="请输入路由地址" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12" v-if="form.type == 'C'">-->
<!--            <el-form-item label="组件路径" prop="component">-->
<!--              <el-input v-model="form.component" placeholder="请输入组件路径" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item v-if="form.type != 'M'" label="权限标识" >-->
<!--              <el-input v-model="form.perms" placeholder="请输入权限标识" maxlength="50" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item label="显示排序" prop="sort">-->
<!--              <el-input-number v-model="form.sort" controls-position="right" :min="0" />-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12" v-if="form.type == 'C'">-->
<!--            <el-form-item label="是否缓存">-->
<!--              <el-radio-group v-model="form.noCache">-->
<!--                <el-radio-->
<!--                  v-for="dict in cacheOptions"-->
<!--                  :key="dict.value"-->
<!--                  :label="dict.value"-->
<!--                >{{dict.label}}</el-radio>-->
<!--              </el-radio-group>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
<!--          <el-col :span="12">-->
<!--            <el-form-item v-if="form.type != 'F'" label="菜单状态">-->
<!--              <el-radio-group v-model="form.status">-->
<!--                <el-radio-->
<!--                  v-for="dict in statusOptions"-->
<!--                  :key="dict.value"-->
<!--                  :label="dict.value"-->
<!--                >{{dict.label}}</el-radio>-->
<!--              </el-radio-group>-->
<!--            </el-form-item>-->
<!--          </el-col>-->
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import { listProduct} from "@/api/system/product";
  import {listApplication} from "@/api/system/application";
  import Treeselect from "@riophae/vue-treeselect";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import IconSelect from "@/components/IconSelect";
  import store from "@/store";
  import { VueCropper } from "vue-cropper";
  export default {
    name: "Menu",
    components: { Treeselect, IconSelect,VueCropper },
    data() {
      return {
        // 遮罩层
        loading: true,
        // 菜单表格树数据
        menuList: [],
        // 菜单树选项
        menuOptions: [],
        // 弹出层标题
        title: "",
        productList:null,
        // 是否显示弹出层
        open: false,
        // 菜单状态数据字典
        statusOptions: [],
        // 缓存数据字典
        cacheOptions: [],
        applicationOptions: [],
        // 查询参数
        queryParams: {
          productName: undefined,
          productPrice: undefined,
          productDetail:undefined,
          productDesc:undefined,
          salerMobile:undefined,
          groud:undefined
        },
        previews: {},
        options: {
          img: store.getters.avatar, //裁剪图片的地址
          autoCrop: true, // 是否默认生成截图框
          autoCropWidth: 200, // 默认生成截图框宽度
          autoCropHeight: 200, // 默认生成截图框高度
          fixedBox: true // 固定截图框大小 不允许改变
        },
        // 显示搜索条件
        showSearch: true,
        // 表单参数
        form: {},
        // 表单校验
        rules: {
          applicationId: [
            { required: true, message: "所属应用不能为空", trigger: "blur" }
          ],
          name: [
            { required: true, message: "菜单名称不能为空", trigger: "blur" }
          ],
          sort: [
            { required: true, message: "菜单顺序不能为空", trigger: "blur" }
          ],
          path: [
            { required: true, message: "路由地址不能为空", trigger: "blur" }
          ]
        }
      };
    },
    created() {
      this.getList();
      // this.getAppList();
      // this.getDicts("menu_status").then(response => {
      //   this.statusOptions = response.data;
      // });
      // this.getDicts("yes_no").then(response => {
      //   this.cacheOptions = response.data;
      // });
    },
    methods: {
      // 选择图标
      selected(name) {
        this.form.icon = name;
      },
      /** 查询菜单列表 */
      getList() {
        this.loading = true;
        listProduct(this.queryParams).then(response => {
          this.productList=response.data;
          this.total = response.total;
          this.loading = false;
          // alert(response.data);
          // this.menuList = this.handleTree(response.data, "id");
          // this.loading = false;
        });
      },
      /** 查询应用列表 */
      getAppList() {
        this.loading = true;
        listApplication({current: 1, size: 30}).then(response => {
            this.applicationOptions = response.data;
            this.loading = false;
          }
        );
      },
      /** 转换菜单数据结构 */
      normalizer(node) {
        if (node.children && !node.children.length) {
          delete node.children;
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children
        };
      },
      // 上传图片
      uploadImg() {
        this.$refs.cropper.getCropBlob(data => {
          let formData = new FormData();
          formData.append("avatarfile", data);
          uploadAvatar(formData).then(response => {
            if (response.code === 0) {
              this.open = false;
              store.settings.actions.setAvatar(response.data);
              this.options.img = process.env.VUE_APP_BASE_API + response.data;
              this.msgSuccess("修改成功");
            } else {
              this.msgError(response.msg);
            }
            this.$refs.cropper.clearCrop();
          });
        });
      },
      // 实时预览
      realTime(data) {
        this.previews = data;
      },
      /** 查询菜单下拉树结构 */
      getTree() {
        listMenu().then(response => {
          this.menuOptions = [];
          const menu = { id: 0, name: '主类目', children: [] };
          menu.children = this.handleTree(response.data, "id");
          this.menuOptions.push(menu);
        });
      },
      // 菜单显示状态字典翻译
      statusFormat(row, column) {
        if (row.type == "F") {
          return "";
        }
        return this.selectDictLabel(this.statusOptions, row.status);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          parentId: 0,
          name: undefined,
          icon: undefined,
          type: "M",
          sort: undefined,
          noCache: "1",
          status: "0"
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.current = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
      },
      /** 新增按钮操作 */
      handleAdd(row) {
        this.reset();
        // this.getTree();
        // if (row != null) {
        //   this.form.parentId = row.id;
        // }
        this.open = true;
        this.title = "添加商品";
      },
      /** 修改按钮操作 */
      handleEdit(row) {
        this.reset();
        this.getTree();
        getMenu(row.id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改菜单";
        });
      },
      /** 提交按钮 */
      submitForm: function() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if(this.form.type === 'F' && !this.form.perms){
              this.msgError("权限标识不能为空！");
              return;
            }
            if (this.form.id != undefined) {
              editMenu(this.form).then(response => {
                if (response.code === 0) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            } else {
              console.log(JSON.stringify(this.form))
              addMenu(this.form).then(response => {
                if (response.code === 0) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                } else {
                  this.msgError(response.msg);
                }
              });
            }
          }
        });
      },
      editCropper() {
        this.open = true;
      },
      // 覆盖默认的上传行为
      requestUpload() {
      },
      // 向左旋转
      rotateLeft() {
        this.$refs.cropper.rotateLeft();
      },
      // 向右旋转
      rotateRight() {
        this.$refs.cropper.rotateRight();
      },
      // 图片缩放
      changeScale(num) {
        num = num || 1;
        this.$refs.cropper.changeScale(num);
      },
      // 上传预处理
      beforeUpload(file) {
        if (file.type.indexOf("image/") == -1) {
          this.msgError("文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。");
        } else {
          const reader = new FileReader();
          reader.readAsDataURL(file);
          reader.onload = () => {
            this.options.img = reader.result;
          };
        }
      },
      /** 删除按钮操作 */
      handleDel(row) {
        this.$confirm('是否确认删除名称为"' + row.name + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delMenu(row.id);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(function() {});
      }
    }
  };
</script>
